<?php

namespace app\api\model\cps;

use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;
use think\Log;


class Pdd
{
    protected $client_id = '95fe9086e3db404f92b3e6e37da48744';

    protected $client_secret = '68a5077950b29a7f4436b9d49157523b06beceee';

    public $custom_parameters = ['uid'=>1];

    //媒体id 10088204164

    //多多进宝商品查询
    public function goodsList($page,$keyword,$cat_id)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'client_id' => $this->client_id,
            'custom_parameters'=>json_encode($this->custom_parameters,320),
            'page'=>$page,
            'opt_id'=>$cat_id,
            'keyword'=>$keyword,
            'pid'=>'41195366_292109156',
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.search',
        ];

        //商品关键词
        /*if ($keyword){
            $data['keyword'] = $keyword;
        }*/
        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);

        $goods_list = $res['goods_search_response'];

        foreach ($goods_list['goods_list'] as $k=>$v){
            $goods_list['goods_list'][$k]['wawa_commission'] =  round($v['min_group_price']/100*$v['promotion_rate']/1000*0.56,2);
        }
        return $goods_list;
    }

    //多多进宝商品详情
    public function goodsDetail($goods_sign)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";


        $data = [
            'client_id' => $this->client_id,
            'goods_sign'=>$goods_sign,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.detail',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        $goods_detail = $res['goods_detail_response'];
        foreach ($goods_detail['goods_details'] as $k=>$v){
            $goods_detail['goods_details'][$k]['wawa_commission'] =  round($v['min_group_price']/100*$v['promotion_rate']/1000*0.56,2);
        }

        return $goods_detail;
    }

    //多多进宝商品推荐
    public function recommendGoods($activity_tags,$limit,$offset)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'activity_tags'=>$activity_tags,//活动商品标记数组，例：[4,7]，4-秒杀，7-百亿补贴，
            //10851-千万补贴，11879-千万神券，10913-招商礼金商品，31-品牌黑标，10564-精选爆品-官方直推爆款，
            //10584-精选爆品-团长推荐，24-品牌高佣，其他的值请忽略
            'client_id' =>  $this->client_id,
            'offset'=>$offset,
            'limit'=>$limit,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.recommend.get',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        $goods_list = $res['goods_basic_detail_response'];
        foreach ($goods_list['list'] as $k=>$v){
            $goods_list['list'][$k]['wawa_commission'] =  round($v['min_group_price']/100*$v['promotion_rate']/1000*0.56,2);
        }
        return $goods_list;
    }

    //多多进宝推广链接生成
    public function url($goods_sign_list,$p_id,$user_id)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";
        $custom_parameters = [
            'uid'=>1,
            'sid'=>$user_id
        ];
        //dump(json_encode(_json_decode($goods_sign_list),320));
        $data = [
            'client_id' =>  $this->client_id,
            'goods_sign_list'=>json_encode(_json_decode($goods_sign_list),320),
            'p_id'=>$p_id,
            'custom_parameters'=>json_encode($custom_parameters,320),
            'generate_we_app'=>'true',
            //'generate_weixin_code'=>'true',
            'generate_short_link'=>'true',
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.promotion.url.generate',
        ];
        Log::error('pdd商品转链:url');
        Log::error(json_encode($data,320));

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res['goods_promotion_url_generate_response'];
    }


    //查询未结算的订单
    public function unliquidated()
    {
        $detail = UserConsumeLog::where(['cps_type'=>1,'consume_type'=>2,'is_to_account'=>0,'is_common'=>0])
            ->field('pay_time')->order('pay_time asc')->find();
        if ($detail){
            $pay_time = $detail['pay_time'];
            $start = date('Y-m-d H:i:s',$pay_time-86400*15);
            $end = date('Y-m-d H:i:s',$pay_time+86400);
            $res = $this->orderlist(1,$start,$end);
        }

        /*foreach ($lists as $k=>$v){
            $start = date('Y-m-d H:i:s',$v['pay_time']-3600);
            $end = date('Y-m-d H:i:s',$v['pay_time']);
            $res = $this->orderlist(1,$start,$end);
        }*/
    }

    //查询推广订单
    public function orderlist($type=0,$start='',$end='')
    {
        $api = "http://gw-api.pinduoduo.com/api/router";
        //dump(strtotime("-6 month"));die;
        $start_time = date('Y-m-d H:i:s',time()-3600);
        $end_time = date('Y-m-d H:i:s',time());
        if ($type==1){
            $start_time = $start;
            $end_time = $end;
        }
        $data = [
            'client_id' =>  $this->client_id,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.order.list.range.get',
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'page_size'=>300
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);

        $order_list = $res['order_list_get_response'];
        foreach ($order_list['order_list'] as $k=>$v){
            $custom_parameters = json_decode($v['custom_parameters'],true);

            if (array_key_exists('sid',$custom_parameters)){

                $user = User::get($custom_parameters['sid']);

                if ($user){
                    $promotion_amount = $v['promotion_amount']/100;
                    $commission = $promotion_amount*0.56;
                    //增加消费记录
                    $consume_log_info = UserConsumeLog::get([ 'user_id'=>$custom_parameters['sid'], 'order_no'=>$v['order_sn']]);
                    if (!$consume_log_info){
                        $consume_log_model = new UserConsumeLog();
                        $consume_log_data = [
                            'user_id'=>$custom_parameters['sid'],
                            'title'=>$v['goods_name'],
                            'shop_id'=>$v['mall_id'],
                            'shop_name'=>$v['mall_name'],
                            'image'=>$v['goods_thumbnail_url'],
                            'order_no'=>$v['order_sn'],
                            'pay_time'=>$v['order_pay_time'],
                            'pay_price'=>$v['order_amount']/100,
                            'consume_type'=>2,
                            'cps_type'=>1,
                            'goods_id'=>$v['goods_sign'],
                            'commission'=>$commission,
                            'total_commission'=>$promotion_amount,
                            'order_status_name'=>'已付款'
                        ];
                        User::update(['is_buy'=>1],['id'=>$custom_parameters['sid']]);

                        $user_model = new User();
                        $user_model->upgrade($custom_parameters['sid']);
                        $consume_log_model->save($consume_log_data);
                        UserConsumeLog::lockMemberConsumeCalculate($custom_parameters['sid'],$consume_log_model->total_commission,$consume_log_model->consume_id,0);
                        UserConsumeLog::newrecommendShopConsumeCalculate($custom_parameters['sid'],0,$consume_log_model->total_commission,$consume_log_model->consume_id,2);
                    } else {
                        if ($v['order_status']==5&&$consume_log_info->is_to_account==0){
                            //发放消费记录的收益
                            UserConsumeLog::sendCommission($consume_log_info->order_no);
                        } elseif ($v['order_status']==2&&$v['order_receive_time']>0){
                            $consume_log_info->receive_time = $v['order_receive_time'];
                            $consume_log_info->save();
                        } elseif($v['order_status']==4||$v['order_status']==10&&$consume_log_info->is_refund==0) {
                            $consume_log_info->commission = 0;
                            $consume_log_info->order_status_name = '退款成功';
                            $consume_log_info->is_refund = 1;
                            $consume_log_info->save();
                            ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                            ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                        }
                    }
                }

            }

        }

        return $order_list;
    }

    //创建多多进宝推广位
    public function promotionbit($number,$media_id)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'client_id' =>  $this->client_id,
            'number'=>$number,
            'media_id'=>$media_id,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.pid.generate',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    //查询已经生成的推广位信息
    public function promotionbitlist($page)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'client_id' =>  $this->client_id,
            'page'=>$page,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.pid.query',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    //批量绑定推广位的媒体id
    public function promotionbitBind($media_id,$pid_list)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'client_id' =>  $this->client_id,
            'media_id'=>$media_id,
            'pid_list'=>json_encode(_json_decode($pid_list),320),
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.pid.mediaid.bind',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    //多多进宝转链接口
    public function uniturl($pid,$source_url)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";

        $data = [
            'client_id' =>  $this->client_id,
            'pid'=>$pid,//渠道id
            'custom_parameters'=>json_encode($this->custom_parameters,320),
            'generate_short_link'=>'true',
            'source_url'=>$source_url,//需转链的链接，支持拼多多商品链接、进宝长链/短链（即为pdd.ddk.goods.promotion.url.generate接口生成的长短链）
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.goods.zs.unit.url.gen',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    //生成备案链接
    public function beianurl($goods_sign,$p_id,$channel_type)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";
        //dump(json_encode(_json_decode($goods_sign_list),320));

        $p_id = ['41195366_292109156'];
        $data = [
            'client_id' =>  $this->client_id,
            'goods_sign'=>$goods_sign,
            'p_id_list'=>json_encode($p_id,320),
            'custom_parameters'=>json_encode($this->custom_parameters,320),
            'channel_type'=>$channel_type,
            'generate_we_app'=>'true',
            'generate_short_url'=>'true',
            'generate_schema_url'=>'true',
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.rp.prom.url.generate',
        ];

        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    //多多进宝频道推广
    public function resourceurl($resource_type,$pid,$user_id)
    {
        $api = "http://gw-api.pinduoduo.com/api/router";
        //dump(json_encode(_json_decode($goods_sign_list),320));
        $custom_parameters = [
            'uid'=>1,
            'sid'=>$user_id
        ];
        $data = [
            'client_id' =>  $this->client_id,
            'pid'=>$pid,
            'custom_parameters'=>json_encode($custom_parameters,320),
            'resource_type'=>$resource_type,
            'timestamp'=>time(),
            'type'=> 'pdd.ddk.resource.url.gen',
        ];
        Log::error('pdd活动转链:resourceurl');
        Log::error(json_encode($data,320));
        //dump($data);die;
        $sign = $this->getSign($data);
        $data['sign'] = $sign;

        $res = https_request($api,$data);
        $res = json_decode($res,true);
        return $res;
    }

    public function getSign($requestData)
    {
        // 生成签名
        ksort($requestData);
        $signStr = $this->client_secret;
        foreach ($requestData as $key => $value) {
            $signStr .= $key . $value;
        }
        $signStr .= $this->client_secret;
        $sign = strtoupper(md5($signStr));
        return $sign;
    }


}